package com.zhhs.project.act.activity.controller;


import com.qcloud.cos.utils.IOUtils;
import com.zhhs.common.utils.poi.ExcelUtil;
import com.zhhs.framework.aspectj.lang.annotation.Log;
import com.zhhs.framework.aspectj.lang.enums.BusinessType;
import com.zhhs.framework.config.RuoYiConfig;
import com.zhhs.framework.web.controller.BaseController;
import com.zhhs.framework.web.domain.AjaxResult;
import com.zhhs.framework.web.page.TableDataInfo;
import com.zhhs.project.act.activity.domian.ActActivityUserAward;
import com.zhhs.project.act.activity.domian.ActivityAwardVo;
import com.zhhs.project.act.activity.domian.AwardVo;
import com.zhhs.project.act.activity.service.IActActivityUserAwardService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;

/**
 * 活动核销Controller
 *
 * @author zhhs
 * @date 2022-11-09
 */
@RestController
@RequestMapping("/wecom/activity/actaward")
public class ActActivityUserAwardController extends BaseController
{

    @Autowired
    private IActActivityUserAwardService actActivityUserAwardService;


    /**
     * 查询活动核销列表
     */
    @PreAuthorize("@ss.hasPermi('zhhs:activityuseraward:list')")
    @GetMapping("/list/{actId}")
    public TableDataInfo list(@PathVariable Long actId, ActActivityUserAward actActivityUserAward)
    {
        startPage();
        List<AwardVo> awardVos = actActivityUserAwardService.selectAwardList(actId,actActivityUserAward);
        return getDataTable(awardVos);
    }

    /**
     * 导出活动核销列表
     */
    @PreAuthorize("@ss.hasPermi('zhhs:activityuseraward:export')")
    @Log(title = "活动核销", businessType = BusinessType.EXPORT)
    @GetMapping("/export/{id}")
    public AjaxResult export(@PathVariable Long id) throws IOException {
        ActActivityUserAward actActivityUserAward = new ActActivityUserAward();
        List<AwardVo> awardVos = actActivityUserAwardService.selectAwardList(id,actActivityUserAward);
        ExcelUtil<AwardVo> util = new ExcelUtil<AwardVo>(AwardVo.class);
        return util.exportExcel(awardVos, "活动核销数据");
    }
//
//    public static void main(String[] args) {
//        BasicTextEncryptor encryptor = new BasicTextEncryptor();
//        encryptor.setPassword("zhhs");
//        encryptor.decrypt("DSt3bZ7/EjEpNzxv8EFT2wuERPdefOTBpiWpqvn951O/TGoHmrsBCw==");
//    }


    public void  excelUpdate(List<AwardVo> awardVos) throws IOException {
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        // 创建工作表
        Sheet sheet = workbook.createSheet("活动核销数据");
        // 设置默认列宽为 5
        sheet.setDefaultColumnWidth(20);

        // 设置默认行高为 5
        sheet.setDefaultRowHeightInPoints(20);
        // 在工作表中创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("用户编号");
        headerRow.createCell(1).setCellValue("用户昵称");
        headerRow.createCell(2).setCellValue("奖品等级");
        headerRow.createCell(3).setCellValue("奖品名称");
        headerRow.createCell(4).setCellValue("获奖时间");
        headerRow.createCell(5).setCellValue("核销状态");
        headerRow.createCell(6).setCellValue("用户头像");
        headerRow.createCell(7).setCellValue("姓名");
        headerRow.createCell(8).setCellValue("电话");
        headerRow.createCell(9).setCellValue("省份");
        headerRow.createCell(10).setCellValue("地市");
        headerRow.createCell(11).setCellValue("区县");
        headerRow.createCell(12).setCellValue("地址详情");

        // 根据用户数据填充工作表
        int rowNum = 1;
        for (AwardVo awardVo : awardVos) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(awardVo.getId());
            row.createCell(1).setCellValue(awardVo.getNickname());
            row.createCell(2).setCellValue(awardVo.getPrizeLevel());
            row.createCell(3).setCellValue(awardVo.getPrizeName());
            row.createCell(4).setCellValue(awardVo.getCreateTime());
            row.createCell(5).setCellValue(awardVo.getStatus());
            row.createCell(6).setCellValue(awardVo.getProfile());
            row.createCell(7).setCellValue(awardVo.getName());
            row.createCell(8).setCellValue(awardVo.getPhoneNumber());
            row.createCell(9).setCellValue(awardVo.getProvince());
            row.createCell(10).setCellValue(awardVo.getCity());
            row.createCell(11).setCellValue(awardVo.getCounty());
            row.createCell(12).setCellValue(awardVo.getAddressDetail());
            // 处理用户头像链接并插入图片
            String avatarUrl = awardVo.getProfile();
            if (avatarUrl != null && !avatarUrl.isEmpty()) {
                insertImage(sheet, row,6, avatarUrl);
            }
        }
        // 导出 Excel 文件
        String downloadPath = RuoYiConfig.getDownloadPath() + "活动核销数据.xlsx";
        FileOutputStream outputStream = new FileOutputStream(downloadPath);
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();
        System.out.println("Excel exported successfully.");
    }
    // 插入图片并调整大小为 100x100 像素
    private static void insertImage(Sheet sheet, Row row, int rowNum, String imageUrl) throws IOException {
        // 获取图片的字节流
        URL url = new URL(imageUrl);
        InputStream imageStream = url.openStream();
        byte[] imageBytes = IOUtils.toByteArray(imageStream);
        imageStream.close();

        // 将图片插入到工作表中
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        CreationHelper helper = sheet.getWorkbook().getCreationHelper();
        ClientAnchor anchor = helper.createClientAnchor();
        int pictureIndex = sheet.getWorkbook().addPicture(imageBytes, Workbook.PICTURE_TYPE_JPEG);
        anchor.setCol1(6);
        anchor.setRow1(row.getRowNum());
        Picture picture = drawing.createPicture(anchor, pictureIndex);
        // 调整图片大小为 100x100 像素
        picture.resize(5, 5);
    }


    /**
     * 新增保存活动核销
     */
    @PreAuthorize("@ss.hasPermi('zhhs:activityuseraward:add')")
    @Log(title = "活动核销", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addSave(ActActivityUserAward actActivityUserAward)
    {
        return toAjax(actActivityUserAwardService.insertActActivityUserAward(actActivityUserAward));
    }



    /**
     * 修改保存活动核销
     */
    @PreAuthorize("@ss.hasPermi('zhhs:activityuseraward:edit')")
    @Log(title = "活动核销", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editSave(@RequestBody ActActivityUserAward actActivityUserAward)
    {
        return toAjax(actActivityUserAwardService.updateActActivityUserAward(actActivityUserAward));
    }

    /**
     * 删除活动核销
     */
    @PreAuthorize("@ss.hasPermi('zhhs:activityuseraward:remove')")
    @Log(title = "活动核销", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    public AjaxResult remove(String ids)
    {
        return toAjax(actActivityUserAwardService.deleteActActivityUserAwardByIds(ids));
    }

    /**
     * 查询活动信息
     * @param activityId
     * @return
     */
    @PostMapping("/activity")
    public AjaxResult activity( Long activityId)
    {
        ActivityAwardVo activityVo = actActivityUserAwardService.selectActivity(activityId);
        return AjaxResult.success(activityVo);
    }
}
